// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
//   2013 Petar Maymounkov <p@gocircuit.org>

package ripple

import (
	"io"
	"os"
	"strconv"
	"sync"

	"circuit/kit/rh"
)

func MustDupFID(fid rh.FID) rh.FID {
	_fid, err := fid.Walk(nil)
	if err != nil {
		panic(err)
	}
	return _fid
}

func uid() string {
	return strconv.Itoa(os.Getuid())
}

func gid() string {
	return strconv.Itoa(os.Getgid())
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

// un of the "defer un(lock(m))" Locker pattern
func un(l sync.Locker) {
	l.Unlock()
}

// lock of the "defer un(lock(m))" Locker pattern
func lock(l sync.Locker) sync.Locker {
	l.Lock()
	return l
}

func runOnClose(r io.Reader, f func()) io.ReadCloser {
	var once sync.Once
	return &roc{
		Reader: r,
		roc: func() {
			if f != nil {
				once.Do(f)
			}
		},
	}
}

type roc struct {
	io.Reader
	roc func()
}

func (r *roc) Close() error {
	r.roc()
	return nil
}
